/*
 * Copyright (C) 2016-2019 Samuel Wall
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package uk.co.samuelwall.materialtaptargetprompt.sample;

import ohos.aafwk.ability.Ability;
import ohos.aafwk.ability.fraction.Fraction;
import ohos.aafwk.content.Intent;
import ohos.agp.animation.Animator;
import ohos.agp.components.Component;
import ohos.agp.components.ComponentContainer;
import ohos.agp.components.DependentLayout;
import ohos.agp.components.DirectionalLayout;
import ohos.agp.components.LayoutScatter;
import ohos.agp.components.PageSlider;
import ohos.agp.components.PageSliderProvider;
import ohos.agp.components.Text;
import ohos.agp.window.dialog.CommonDialog;
import uk.co.samuelwall.materialtaptargetprompt.MaterialTapTargetPrompt;
import uk.co.samuelwall.materialtaptargetprompt.extras.focals.RectanglePromptFocal;
import uk.co.samuelwall.materialtaptargetprompt.sample.utils.NumUtil;

/**
 * Prompt example for {@link CommonDialog}.
 *
 * @since 2021-06-21
 */
public class SupportDialogFragmentExample extends Fraction {
    private final String[] tabStrings = new String[]{"", "Page0", "Page1", "Page2", "Page3", "Page4", "Page5", ""};
    private Text tabText1;
    private Text tabText2;
    private Text tabText3;
    private int selectedPosition = 1;
    private boolean isSelecting = false;
    private ComponentContainer mRootView;
    private DirectionalLayout tabDl;
    private PageProvider mPageProvider;
    private MainAbility mainAbility;
    /**
     * PageSlider
     */
    private PageSlider viewPager;

    /**
     * onComponentAttached
     *
     * @param scatter scatter
     * @param container container
     * @param intent intent
     * @return Component
     */
    @Override
    protected Component onComponentAttached(LayoutScatter scatter, ComponentContainer container, Intent intent) {
        // 返回指定的页面
        return scatter.parse(ResourceTable.Layout_support_fragment_dialog, container, false);
    }

    public void setAbility(Ability ability) {
        mainAbility = (MainAbility)ability;
    }

    /**
     * onStart
     *
     * @param intent intent
     */
    protected void onStart(Intent intent) {
        super.onStart(intent);
        initViews();
    }

    private void initViews() {
        mRootView = (ComponentContainer)getFractionAbility().findComponentById(ResourceTable.Id_fraction_view);
        mRootView.setClickedListener(component -> {
        });
        viewPager = (PageSlider) getFractionAbility().findComponentById(ResourceTable.Id_page_slider);
        DependentLayout fractionDl = (DependentLayout)
                getFractionAbility().findComponentById(ResourceTable.Id_fraction_dl);
        fractionDl.setClickedListener(component -> {
            mainAbility.hideFraction();
        });
        initPages();
        initTabs();
        getFractionAbility().findComponentById(ResourceTable.Id_text_fab_prompt)
                .setClickedListener(view -> showFragmentFabPrompt());
        getFractionAbility().findComponentById(ResourceTable.Id_button_view_pager_prompt)
                .setClickedListener(v -> showViewPagerTab());
    }

    private void initPages() {
        mPageProvider = new PageProvider(this);
        viewPager.setProvider(mPageProvider);

        // 设置PageSlider的属性
        viewPager.setOrientation(Component.HORIZONTAL);
        viewPager.setSlidingPossible(true);

        // 设置PageSlider页面改变时的监听
        viewPager.addPageChangedListener(new PageSlider.PageChangedListener() {
            @Override
            public void onPageSliding(int itemPos, float itemPosOffset, int itemPosOffsetPixels) {
            }

            @Override
            public void onPageSlideStateChanged(int state) {
            }

            @Override
            public void onPageChosen(int itemPos) {
            }
        });
        viewPager.setCurrentPage(selectedPosition - 1);
        showPrompt(mPageProvider.getComponent(0));
        showFragmentFabPrompt();
        mPageProvider.getComponent(0).setClickedListener(component -> showPrompt(mPageProvider.getComponent(0)));
    }

    private void initTabs() {
        tabDl = (DirectionalLayout) getFractionAbility().findComponentById(ResourceTable.Id_tab_dl);
        tabText1 = (Text) getFractionAbility().findComponentById(ResourceTable.Id_tab1_txt);
        tabText2 = (Text) getFractionAbility().findComponentById(ResourceTable.Id_tab2_txt);
        tabText3 = (Text) getFractionAbility().findComponentById(ResourceTable.Id_tab3_txt);
        tabText1.setClickedListener(component -> {
            if (selectedPosition > 1 && !isSelecting) {
                isSelecting = true;
                selectedPosition--;
                viewPager.setCurrentPage(0);
                setTabText();
            }
        });
        tabText3.setClickedListener(component -> {
            if (selectedPosition < NumUtil.INT_6 && !isSelecting) {
                isSelecting = true;
                selectedPosition++;
                viewPager.setCurrentPage(0);
                setTabText();
            }
        });
    }

    private void setTabText() {
        tabText1.setText(tabStrings[selectedPosition - 1]);
        tabText2.setText(tabStrings[selectedPosition]);
        tabText3.setText(tabStrings[selectedPosition + 1]);
        showPrompt(mPageProvider.getComponent(0));
        isSelecting = false;
    }

    /**
     * PageProvider
     *
     * @since 2021-06-21
     */
    public static class PageProvider extends PageSliderProvider {
        private SupportDialogFragmentExample mFraction;
        private Component[] btnList;

        /**
         * PageProvider
         *
         * @param fraction fraction
         */
        public PageProvider(Fraction fraction) {
            mFraction = (SupportDialogFragmentExample) fraction;
            btnList = new Component[]{new Component(mFraction)};
        }

        @Override
        public int getCount() {
            return btnList.length;
        }

        @Override
        public Object createPageInContainer(ComponentContainer componentContainer, int position) {
            Component cpt = LayoutScatter.getInstance(mFraction.getFractionAbility())
                    .parse(ResourceTable.Layout_fragment_view_pager, componentContainer, false);
            btnList[position] = cpt.findComponentById(ResourceTable.Id_button);
            componentContainer.addComponent(cpt);
            return cpt;
        }

        /**
         * getComponent
         *
         * @param position position
         * @return Component
         */
        public Component getComponent(int position) {
            return btnList[position];
        }

        @Override
        public void destroyPageFromContainer(ComponentContainer componentContainer, int position, Object obj) {
            if (componentContainer == null) {
                return;
            }
            if (obj instanceof Component) {
                componentContainer.removeComponent((Component) obj);
            }
        }

        @Override
        public boolean isPageMatchToObject(Component component, Object o) {
            return true;
        }
    }

    private void showFragmentFabPrompt() {
        new MaterialTapTargetPrompt.Builder(this, mRootView)
                .setTarget(ResourceTable.Id_fraction_fab)
                .setAnimationCurveType(Animator.CurveType.ACCELERATE_DECELERATE)
                .setPrimaryText("Clipped to dialog bounds")
                .setSecondaryText("The prompt does not draw outside the dialog")
                .setClipToView(mRootView)
                .show();
    }

    private void showViewPagerTab() {
        new MaterialTapTargetPrompt.Builder(this, mRootView)
                .setTarget(tabDl)
                .setPromptFocal(new RectanglePromptFocal(getFractionAbility()))
                .setAnimationCurveType(Animator.CurveType.ACCELERATE_DECELERATE)
                .setPrimaryText("View Pager Tab")
                .setSecondaryText("Change tab")
                .setClipToView(mRootView)
                .show();
    }

    /**
     * showPrompt
     *
     * @param component component
     */
    public void showPrompt(Component component) {
        new MaterialTapTargetPrompt.Builder(this, mRootView)
                .setTarget(component)
                .setAnimationCurveType(Animator.CurveType.ACCELERATE_DECELERATE)
                .setPrimaryText("Clipped to dialog bounds")
                .setSecondaryText("The prompt does not draw outside the dialog")
                .setClipToView(mRootView)
                .show();
    }
}
